package com.timguan.render.web.common;

import net.pocrd.entity.ServiceException;
import net.pocrd.entity.ServiceRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;

/**
 * Created by guankaiqiang on 2014/12/3.
 */
public abstract class ServiceExceptionListener {
    private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionListener.class);
    private HashSet<Integer> handleCodes = new HashSet<Integer>();

    public ServiceExceptionListener() {
        initAcceptCodes();
    }

    protected void setCodes(int[] codes) {
        if (codes != null && codes.length != 0) {
            for (int i = 0; i < codes.length; i++) {
                handleCodes.add(Integer.valueOf(codes[i]));
            }
        }
    }

    protected void setCode(int code) {
        handleCodes.add(Integer.valueOf(code));
    }

    public boolean accept(int eventCode) {
        if (handleCodes != null) {
            boolean isAccept = handleCodes.contains(Integer.valueOf(eventCode));
            if (isAccept) {
                if (logger.isDebugEnabled()) {
                    logger.debug(this.getClass().getName() + " accept!,code:{}", eventCode);
                }
            }
            return isAccept;
        }
        return false;
    }

    /**
     * 需要关注的错误码
     */
    public abstract void initAcceptCodes();

    /**
     * serviceException观察者
     * 对errorCode进行处理
     *
     * @return
     */
    public abstract ModelAndView serviceExceptionEventHandle(int event, ServiceException se, ServiceRuntimeException sre, HttpServletRequest request, HttpServletResponse response);
}
